﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;
using System.Xml.Linq;

namespace Gpearce.Model
{ 
    public static class YouTubeManager 
    {
        private const string CALABOGIE_YOU_TUBE_USER = "CalabogieResort";
        private const string YOUTUBE_USER_FEED_URL = "http://gdata.youtube.com/feeds/api/users/{0}/uploads";
        private static Action<YouTubeVideoInfo[]> videoHandler; 
        private static Action<Exception, object> videoFailHandler; 

        public static void GetYouTubeFeed(string userName, Action<YouTubeVideoInfo[]> handler, Action<Exception, object> failHandler) 
        { 
            videoHandler = handler; 
            videoFailHandler = failHandler; 
            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); wc.DownloadStringAsync(new Uri(string.Format(YOUTUBE_USER_FEED_URL, userName))); 
        } 

        static void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
        { 
            if (e.Error != null) 
            { 
                videoFailHandler(e.Error, e.UserState); 
            } 
            else 
            { 
                Debug.WriteLine(e.Result); 
                StringReader sr = new StringReader(e.Result); 
                var reader = XmlReader.Create(sr); 
                var document = XDocument.Load(reader); 
                XNamespace atom = "http://www.w3.org/2005/Atom"; 
                var entries = from entry in document.Descendants(atom + "entry") let postedDate = DateTime.Parse(entry.Element(atom + "published").Value) orderby postedDate descending select new YouTubeVideoInfo() { PostedDate = DateTime.Parse(entry.Element(atom + "published").Value), Description = entry.Element(atom + "content").Value, Title = entry.Element(atom + "title").Value }; 
                videoHandler(entries.ToArray()); 
            } 
        } 
         
        public static void UpdateYouTubeCache(ViewModel.YouTubeViewModel youTubeViewModel)
        {
            YouTubeManager.GetYouTubeFeed(CALABOGIE_YOU_TUBE_USER,     //success handler     
                videos =>
                {
                    foreach (YouTubeVideoInfo videoInfo in videos)
                    {
                        youTubeViewModel.Items.Add(videoInfo);
                    }
                },     // fail handler     
                (exc, userState) =>
                {
                    Debug.WriteLine(exc.ToString());
                });
        }

        //Regex Youtube = new Regex("youtu(?:\\.be|be\\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)");            

        //Match youtubeMatch = Youtube.Match(YOUTUBE_VIDEO_URL);           

        //string id = string.Empty;

        //if (youtubeMatch.Success)
        //    id = youtubeMatch.Groups[1].Value; 

        //WebBrowserTask webBrowserTask = new WebBrowserTask();


        //webBrowserTask.URL = "vnd.youtube:"+ id +"?vndapp=youtube_mobile";
        //webBrowserTask.Show();

    } 
}
